<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="入库单号" prop="inventoryNumber">
        <el-input v-model="queryParams.inventoryNumber" placeholder="请输入入库单号" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="入库类型" prop="inventoryType">
        <el-select v-model="queryParams.inventoryType" placeholder="请选择入库类型" clearable>
          <el-option v-for="dict in dict.type.py_instock_type" :key="dict.value" :label="dict.label"
            :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
          <el-option v-for="dict in dict.type.py_documents_status" :key="dict.value" :label="dict.label"
            :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="仓库名称" prop="warehouseId">
        <el-select v-model="queryParams.warehouseId" placeholder="请选择" :style="{ width: '100%' }">
          <el-option v-for="item in warehouseIds" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['inbound:inbound:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['inbound:inbound:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['inbound:inbound:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-s-tools" size="mini" @click="fz">复制</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-user" size="mini" @click="sh"
          v-hasPermi="['inbound:inbound:check']" :disabled="!isAuditEnabled">
          审核
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-s-release" size="mini" @click="cx"
          v-hasPermi="['inbound:inbound:revoke']" :disabled="!isWithdrawalEnabled">撤销</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['inbound:inbound:export']">导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-refresh" size="mini" @click="sx">刷新</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
    <!-- 审核弹出框 -->
    <el-dialog title="审核" :visible.sync="shopen" width="500px">
      <el-form :model="shform">
        <el-form-item label="审核结果" prop="result">
          <el-radio-group v-model="shform.result">
            <el-radio :label="2">通过</el-radio>
            <el-radio :label="1">驳回</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="审核意见" prop="comments">
          <el-input type="textarea" v-model="shform.comments" placeholder="请输入"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitReview">确定</el-button>
        <el-button @click="shresetForm">取消</el-button>
      </span>
    </el-dialog>
    <!-- 撤回提示 -->
    <el-dialog title="提示" :visible.sync="dialogVisible" width="400px">
      <span>是否撤回所选数据？</span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="withdraw">确定</el-button>
      </span>
    </el-dialog>

    <el-table v-loading="loading" :data="inboundList" @selection-change="handleSelectionChange">
  <el-table-column type="selection" width="55" align="center" />
      <el-table-column v-if="false" fixed label="序号1" align="center" prop="inventoryId" width="80"    />
      <el-table-column fixed label="序号" align="center" prop="index" width="80"    />
  <el-table-column fixed label="入库单号" align="center" prop="inventoryNumber" width="160">
    <template slot-scope="scope">
      <span @click="handleRowClick(scope.row)" style="color: blue; cursor: pointer;">
        {{ scope.row.inventoryNumber }}
      </span>
    </template>
  </el-table-column>
  <el-table-column fixed label="入库类型" align="center" prop="inventoryType" width="100">
    <template slot-scope="scope">
      <dict-tag :options="dict.type.py_instock_type" :value="scope.row.inventoryType" />
    </template>
  </el-table-column>
  <el-table-column fixed label="状态" align="center" prop="status" width="100">
    <template slot-scope="scope">
      <dict-tag :options="dict.type.py_documents_status" :value="scope.row.status" />
    </template>
  </el-table-column>
  <el-table-column label="仓库名称" align="center" prop="warehouseName" width="120" />
  <el-table-column label="入库日期" align="center" prop="inboundDate" width="180">
    <template slot-scope="scope">
      <span>{{ parseTime(scope.row.inboundDate, 'yyyy-MM-dd HH:mm:ss') }}</span>
    </template>
  </el-table-column>
  <el-table-column label="关联单号" align="center" prop="relatedNumber" width="160" />
  <el-table-column label="经办人" align="center" prop="userNameJBR" width="100" />
  <el-table-column label="入库数量" align="center" prop="rkNum" width="100" />
      <el-table-column label="入库货品" align="center" prop="productNames" width="280">
        <template slot-scope="scope">
          <el-tooltip :content="scope.row.productNames" placement="top">
            <div>{{ changeProNames(scope.row.productNames) }}</div>
          </el-tooltip>
        </template>
      </el-table-column>
  <el-table-column label="入库金额" align="center" prop="rkAmount" width="120">
    <template slot-scope="scope">
      {{ scope.row.rkAmount.toFixed(2) }}
    </template>
  </el-table-column>
  <el-table-column label="制单人" align="center" prop="userNameZDR" width="100" />
  <el-table-column label="所在部门" align="center" prop="deptName" width="120" />
  <el-table-column label="制单时间" align="center" prop="creationTime" width="180">
    <template slot-scope="scope">
      <span>{{ parseTime(scope.row.creationTime, 'yyyy-MM-dd HH:mm:ss') }}</span>
    </template>
  </el-table-column>
  <el-table-column label="审核人" align="center" prop="userNameSHR" width="100" />
  <el-table-column label="审核时间" align="center" prop="sureDate" width="180">
    <template slot-scope="scope">
      <span>{{ parseTime(scope.row.sureDate, 'yyyy-MM-dd HH:mm:ss') }}</span>
    </template>
  </el-table-column>
  <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="150" fixed="right">
    <template slot-scope="scope">
      <el-button v-if="[0, 1].includes(scope.row.status)" size="mini" type="text" icon="el-icon-edit"
        @click="handleUpdate(scope.row)" v-hasPermi="['inbound:inbound:edit']">修改</el-button>
      <el-button size="mini" type="text" v-if="[0, 1].includes(scope.row.status)" icon="el-icon-delete"
        @click="handleDelete(scope.row)" v-hasPermi="['inbound:inbound:remove']">删除</el-button>
    </template>
  </el-table-column>
</el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改入库管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="入库单号" prop="inventoryNumber">
          <el-input v-model="form.inventoryNumber" placeholder="请输入入库单号" />
        </el-form-item>
        <el-form-item label="入库类型" prop="inventoryType">
          <el-select v-model="form.inventoryType" placeholder="请选择入库类型">
            <el-option v-for="dict in dict.type.py_instock_type" :key="dict.value" :label="dict.label"
              :value="parseInt(dict.value)"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio v-for="dict in dict.type.py_documents_status" :key="dict.value" :label="parseInt(dict.value)">{{
              dict.label }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <!-- <el-form-item label="仓库名称" prop="warehouseName">
          <el-input v-model="form.warehouseName" placeholder="请输入仓库名称" />
        </el-form-item> -->
        <el-form-item label="入库日期" prop="inboundDate">
          <el-input v-model="form.inboundDate" placeholder="请输入入库日期" />
        </el-form-item>
        <el-form-item label="关联单号" prop="relatedNumber">
          <el-input v-model="form.relatedNumber" placeholder="请输入关联单号" />
        </el-form-item>
        <el-form-item label="供应商" prop="supplier">
          <el-input v-model="form.supplier" placeholder="请输入供应商" />
        </el-form-item>
        <el-form-item label="联系人" prop="contactPerson">
          <el-input v-model="form.contactPerson" placeholder="请输入联系人" />
        </el-form-item>
        <el-form-item label="联系方式" prop="contactNumber">
          <el-input v-model="form.contactNumber" placeholder="请输入联系方式" />
        </el-form-item>
        <el-form-item label="经办人" prop="handler">
          <el-input v-model="form.handler" placeholder="请输入经办人" />
        </el-form-item>
        <el-form-item label="入库仓库" prop="storageWarehouse">
          <el-input v-model="form.storageWarehouse" placeholder="请输入入库仓库" />
        </el-form-item>
        <el-form-item label="备注" prop="remarks">
          <el-input v-model="form.remarks" placeholder="请输入备注" />
        </el-form-item>
        <el-form-item label="入库数量" prop="instockNum">
          <el-input v-model="form.instockNum" placeholder="请输入入库数量" />
        </el-form-item>
        <el-form-item label="入库货品" prop="inventoryGoods">
          <el-input v-model="form.inventoryGoods" placeholder="请输入入库货品" />
        </el-form-item>
        <el-form-item label="入库金额" prop="inventoryAmount">
          <el-input v-model="form.inventoryAmount" placeholder="请输入入库金额" />
        </el-form-item>
        <el-form-item label="制单人" prop="creator">
          <el-input v-model="form.creator" placeholder="请输入制单人" />
        </el-form-item>
        <el-form-item label="所在部门" prop="department">
          <el-input v-model="form.department" placeholder="请输入所在部门" />
        </el-form-item>
        <el-form-item label="制单时间" prop="creationTime">
          <el-date-picker clearable v-model="form.creationTime" type="date" value-format="yyyy-MM-dd"
            placeholder="请选择制单时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="审核人" prop="sureMan">
          <el-input v-model="form.sureMan" placeholder="请输入审核人" />
        </el-form-item>
        <el-form-item label="审核时间" prop="sureDate">
          <el-input v-model="form.sureDate" placeholder="请输入审核时间" />
        </el-form-item>
        <el-form-item label="附件信息" prop="attachmentInfo">
          <el-input v-model="form.attachmentInfo" placeholder="请输入附件信息" />
        </el-form-item>
        <el-form-item label="更新人" prop="updaterBy">
          <el-input v-model="form.updaterBy" placeholder="请输入更新人" />
        </el-form-item>
        <el-form-item label="逻辑删除" prop="isDelete">
          <el-input v-model="form.isDelete" placeholder="请输入逻辑删除" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listInbound, getInbound, delInbound, addInbound, updateInbound, updateStatus, selectAllBsWarehouse } from "@/api/inbound/inbound";

export default {
  name: "Inbound",
  dicts: ['py_documents_status', 'py_instock_type'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 入库管理表格数据
      inboundList: [],
      //仓库下拉
      warehouseIds: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      //审核弹出
      shopen: false,
      //撤销弹出
      dialogVisible: false,
      //审核判断
      selectedRows: [], // 选中的行
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        inventoryNumber: null,
        inventoryType: null,
        status: null,
        warehouseId: null
      },
      shform: {
        result: 0, // 默认选择通过，0 代表通过
        comments: ''
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      }
    };
  },

  created() {
    this.getList();
    // 确保selectAllBsWarehouse是一个函数并调用它
    selectAllBsWarehouse().then(response => {
      this.warehouseIds = response.data.map(item => ({
        value: item.warehouseId,
        label: item.warehouseName
      }));
    }).catch(error => {
      console.error('Fetching warehouses failed:', error);
    });
  },
  computed: {
    // 计算属性来检查审核按钮是否可用
    isAuditEnabled() {
      return this.selectedRows.length === 1 && this.selectedRows[0].status === 0; // 只有选中一条状态为 0 的数据时，审核按钮可用
    },
    // 计算属性来检查撤回按钮是否可用
    isWithdrawalEnabled() {
      return this.selectedRows.length === 1 && this.selectedRows[0].status === 0; // 只有选中一条状态为 0 的数据时，撤回按钮可用
    }
  },
  methods: {
    changeProNames(value){
      var arr = [];
      if (typeof value === 'string') {
        arr = value.split(",");
      } else if (Array.isArray(value)) {
        arr = value;
      } else {
        console.error("Invalid type for value:", value);
        arr = [];
      }
      // 如果数组长度小于或等于3，直接连接数组元素
      if (arr.length <= 2) {
        return arr.join('、');
      }
      // 如果数组长度大于3，取前三个元素，然后添加"等X项……"，其中X是数组长度
      var firstThree = arr.slice(0, 2);
      var restCount = arr.length-1;
      return firstThree.join('、') + '等' + restCount + '项……';
    },
    parseTime(time, format) {
      if (!time) return '';
      const date = new Date(time);
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      const hours = String(date.getHours()).padStart(2, '0');
      const minutes = String(date.getMinutes()).padStart(2, '0');
      const seconds = String(date.getSeconds()).padStart(2, '0');

      return format.replace(/yyyy/g, year)
        .replace(/MM/g, month)
        .replace(/dd/g, day)
        .replace(/HH/g, hours)
        .replace(/mm/g, minutes)
        .replace(/ss/g, seconds);
    },

    /** 查询入库管理列表 */
    getList() {
      this.loading = true;
      listInbound(this.queryParams).then(response => {
        console.log('后端响应阿萨:', JSON.stringify(response, null, 2));
        this.inboundList = response.rows.map((item, index) => ({
          ...item,
          index: index + 1
        }));
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        inventoryId: null,
        inventoryNumber: null,
        inventoryType: null,
        status: null,
        warehouseName: null,
        inboundDate: null,
        relatedNumber: null,
        supplier: null,
        contactPerson: null,
        contactNumber: null,
        handler: null,
        storageWarehouse: null,
        remarks: null,
        instockNum: null,
        inventoryGoods: null,
        inventoryAmount: null,
        creator: null,
        department: null,
        creationTime: null,
        sureMan: null,
        sureDate: null,
        attachmentInfo: null,
        updaterBy: null,
        updateTime: null,
        isDelete: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.inventoryId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
      this.selectedRows = selection; // 这里将选中的行赋值给 selectedRows

    },
    /** 新增按钮操作 */
    handleAdd() {
      // this.reset();
      // this.open = true;
      // this.title = "添加入库管理";
      this.$router.push({
        path: '/wms/inbound/inbounds/inboundadd'
      }); // 使用绝对路径
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const inventoryId = row.inventoryId || this.ids
      // getInbound(inventoryId).then(response => {
      //   this.form = response.data;
      //   this.open = true;
      //   this.title = "修改入库管理";
      // });
      this.$router.push( {path:'/wms/inbound/inbounds/inboundupdate',
          query:{
            id: inventoryId
          }})
    },
    /** 复制按钮操作 */
    fz() {

    },
    // 审核
    sh() {

      if (!this.isAuditEnabled) {
        return; // 如果审核按钮被禁用，直接返回
      }
      this.shopen = true; // 打开弹出框
      // 执行审核逻辑
      // this.performAudit(this.selectedRows);

    },
    //详情页面
    handleRowClick(row) {
      this.$router.push({ path: `/inbound/inboundDetail/${row.inventoryId}`, query: { inbound: row } });
    },
    submitReview() {
      console.log('选中:', this.selectedRows[0].inventoryNumber);
      console.log('选中:', this.selectedRows);
      console.log('选中:', this.selectedRows[0].relatedNumber);

      // 提交审核逻辑
      console.log('审核结果:', this.shform.result); // 0 或 1
      // 创建一个包含要发送的数据的对象
      const dataToSend = {
        inventoryNumber: this.selectedRows[0].inventoryNumber,
        status: this.shform.result, // 假设结果是 0 或 1
        relatedNumber: this.selectedRows[0].relatedNumber,
        inventoryType: this.selectedRows[0].inventoryType
      };
      console.log('审核结果:', dataToSend); // 0 或 1
      updateStatus(dataToSend)
        .then(response => {
          console.log('审核提交成功:', response);
          this.getList();
        }).catch(error => {
          console.error('Fetching suppliers failed:', error);
        });
      console.log('审核意见:', this.shform.comments);
      this.shopen = false; // 关闭弹出框
    },
    //撤销按钮
    cx() {
      if (!this.isWithdrawalEnabled) {
        return; // 如果撤销按钮被禁用，直接返回
      }
      this.dialogVisible = true; // 打开弹出框

    },
    withdraw() {
      // 执行撤回逻辑
      this.confirmWithdraw(this.selectedRows);
      this.dialogVisible = false;

    },
    // 撤回操作
    confirmWithdraw(rows) {
      // 启动撤回的逻辑
      console.log('执行撤回操作', rows);
    },
    //刷新
    sx() {

    },
    shresetForm() {
      // 重置表单
      this.shform.result = 0; // 默认选择通过
      this.shform.comments = '';
      this.shopen = false; // 关闭弹出框
    },

    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.inventoryId != null) {
            updateInbound(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addInbound(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const inventoryIds = row.inventoryId || this.ids;
      this.$modal.confirm('是否确认删除入库管理编号为"' + inventoryIds + '"的数据项？').then(function () {
        return delInbound(inventoryIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('inbound/inbound/export', {
        ...this.queryParams
      }, `inbound_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
